# Create your models here.
# models.py

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    id= models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name
from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)

    def __str__(self):
        return self.name

class Image(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    image_path = models.CharField(max_length=255)
    description = models.TextField(null=True, blank=True)
    category = models.ForeignKey(Category, related_name='images', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    def get_average_rating(self):
        # 获取所有评分
        ratings = self.ratings.all()

        # 如果没有评分，返回None
        if not ratings:
            return None

        # 计算总评分
        total_rating = sum([rating.rating_id for rating in ratings])

        # 计算平均评分
        average_rating = total_rating / len(ratings)

        return average_rating

    def get_total_rating(self):
        # 获取所有评分
        ratings = self.ratings.all()

        # 计算总评分
        total_rating = sum([rating.rating_id for rating in ratings])

        return total_rating

class Rating(models.Model):
    id = models.AutoField(primary_key=True)
    rating_id = models.PositiveIntegerField()  # 评分（1-5）
    comment = models.TextField(blank=True, null=True)  # 评论
    created_at = models.DateTimeField(auto_now_add=True)  # 评分创建时间
    image = models.ForeignKey(Image, related_name='ratings', on_delete=models.CASCADE)  # 关联图片
    user = models.ForeignKey(User, on_delete=models.CASCADE)  # 关联用户

    class Meta:
        unique_together = ('image', 'user')  # 确保每个用户只能对每张图片打一次分

    def __str__(self):
        return f'{self.user.username} - {self.image.name}'

    def save(self, *args, **kwargs):
        # 确保评分在1-5之间
        if self.rating_id < 1 or self.rating_id > 5:
            raise ValueError("评分必须在1到5之间")
        super().save(*args, **kwargs)
